package com.nchu.student_score.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nchu.student_score.dataObject.User;
import com.nchu.student_score.mapper.CourseMapper;
import com.nchu.student_score.mapper.TeachTaskMapper;
import com.nchu.student_score.model.Course;
import com.nchu.student_score.service.CourseService;
import com.nchu.student_score.util.Define;
import com.nchu.student_score.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
public class CourseServiceImpl implements CourseService {
    @Autowired
    CourseMapper courseMapper;
    @Autowired
    TeachTaskMapper taskMapper;

    @Override
    public ResultVo<Course> getAllCourse() {
        ResultVo<Course> resultVo = new ResultVo<>();
        resultVo.setList(courseMapper.selectAll());
        return resultVo;
    }

    @Override
    public ResultVo<Course> updateCourse(Course input, Integer oldCourseId) {
        ResultVo<Course> resultVo = new ResultVo<>();
        Course course;

        if(oldCourseId == -1){//新增课程
            course = courseMapper.selectByPrimaryKey(input.getCourseId());
            if(course != null){
                resultVo.setStatus(1);
                resultVo.setMessage("目标课程编号已存在!");
                return resultVo;
            }

            courseMapper.insert(input);
            resultVo.setStatus(0);
            resultVo.setMessage("新增课程 " + input.getCourseId() + " " + input.getCourseName() + " 成功!");
        }
        else{
            if(! Objects.equals(input.getCourseId(), oldCourseId)){//需要修改课程编号
                course = courseMapper.selectByPrimaryKey(input.getCourseId());
                if(course != null){
                    resultVo.setStatus(1);
                    resultVo.setMessage("目标课程编号已存在!");
                    return resultVo;
                }
                //修改教学安排中的课程id
                User user = new User();
                user.setId(String.valueOf(oldCourseId));
                user.setNewId(String.valueOf(input.getCourseId()));
                taskMapper.updateCourseId(user);
                //修改课程
                courseMapper.deleteByPrimaryKey(oldCourseId);
                courseMapper.insert(input);
            }
            else{//无需修改课程编号
                courseMapper.updateByPrimaryKey(input);
            }
            resultVo.setStatus(0);
            resultVo.setMessage("修改课程成功!");
        }

        return resultVo;
    }

    @Override
    public PageInfo<Course> getCourseList(Course course, Integer currPage) {
        if(currPage == null) currPage = 1;
        PageHelper.startPage(currPage, Define.PAGE_SIZE);
        return new PageInfo<>(courseMapper.findCourseList(course));
    }
}
